import { exportJson2Excel } from './to-excel';
import { ElMessage, ElLoading } from 'element-plus';
import { isObject } from '@/utils/is';
import { deepMerge } from '@/utils/index';
/*
     * 导出数据的方法
     * @param {Array} modelValue  为需要导出的table数据
     * @param {String} msg 提示文字
     * @param {Array} field 需要导出的表格字段
     * @param {String} xlsxName 导出的文件名
     */

export function exportDataToXlsx({
    // @ts-ignore
    data,
    msg = '导出成功',
    // @ts-ignore
    field,
    // @ts-ignore
    name,
    loading = false
}) {
    let loadingInstance: any;

    if (loading) {
        loadingInstance = ElLoading.service({
            text: '加载中...',
            background: 'rgba(12, 21, 48, 0.5)',
            target: '.layout'
        });
    }
    if (data.length == 0) {
        ElMessage.warning(msg)
        return;
    }
    let thObj = {};
    if (isObject(field)) {
        for (let [key, value] of Object.entries(field)) {
            // @ts-ignore
            thObj[key] = value.name;
        }
    } else {
        for (let i = 0; i < field.length; i++) {
            let key = field[i].column;
            let name = field[i].name;
            // @ts-ignore
            thObj[key] = name;
        }
    }

    exportData(thObj, deepMerge(data), name).then(() => {
        if (loading) {
            ElMessage.success('导出数据成功')
            setTimeout(() => {
                loadingInstance.close()
            }, 500)
        }
    }).catch(() => {
        if (loading) {
            ElMessage.error("导出失败")
            setTimeout(() => {
                loadingInstance.close()
            }, 500)
        }
    })
}

function exportData(thead: object, tbody: object[], exportName: string) {
    /*
     * 封装为promise对象主要为了导出数据量大时可给与loading提示然后在then中关闭loading 或者使用ES7的同步方法
     * @param {Object} thead 为导出xlsx的表头，字段应该为后台数据字段才能一一对应
     * @param {Array} tbody 数据集合
     * @param {String} exportName 导出的文件名
     */
    return new Promise((resolve): void => {
        let th: string[] = [];
        const filterVal: string[] = [];
        for (let i in thead) {
            // @ts-ignore
            th.push(thead[i]);
            filterVal.push(i)
        }
        const [fileName] = [exportName];
        const data = tbody.map(v => filterVal.map(k => {
            // @ts-ignore
            return v[k] || v[k] === 0 ? v[k].toString() : v[k]
        }));
        exportJson2Excel(th, data, fileName);
        resolve(data)
    })
}